package com.itheima.appserver.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.itheima.appserver.config.HuanXinConfig;
import com.itheima.appserver.service.TokenService;
import com.itheima.commons.constants.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.sql.Struct;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

@Service
public class TokenServiceImpl implements TokenService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    @Autowired
    private HuanXinConfig huanXinConfig;


    @Override
    public String getToken() {
        String token = redisTemplate.opsForValue().get(Constants.HX_USER_PREFIX + "token");
        if (StrUtil.isNotBlank(token)) {
            return token;
        }
        return refreshToken();
    }

    @Override
    public String refreshToken() {
        String targetUrl = huanXinConfig.getUrl() + huanXinConfig.getOrgName() + "/" + huanXinConfig.getAppName() + "/token";
        //请求体参数
        Map<String,Object> map = new HashMap<>();
        map.put("grant_type","client_credentials");
        map.put("client_id",huanXinConfig.getClientId());
        map.put("client_secret",huanXinConfig.getClientSecret());

        HttpResponse response = HttpRequest.post(targetUrl)
                .body(JSONUtil.toJsonStr(map))
                .timeout(20000)
                .execute();
        if (response.isOk()){
            //获取响应体
            String body = response.body();
            //解析响应体
            JSONObject jsonObject = JSONUtil.parseObj(body);
            //获得token
            String token = jsonObject.getStr("access_token");
            if (StrUtil.isNotEmpty(targetUrl)) {
                //将token存入redis中 缓存在expires_in 中
                long timeout =jsonObject.getLong("expires_in") - 3600;
                redisTemplate.opsForValue().set(Constants.HX_USER_PREFIX + "token", token, timeout, TimeUnit.SECONDS);
                return token;
            }
        }
        return null;
    }
}
